<template>
  <div class="app-container">
    <el-card class="table_style">
      <el-form ref="ruleForm" :model="notice" :rules="rules" label-width="100px">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="notice.title" />
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <quill-editor ref="QuillEditor" v-model="notice.content" :options="editorOption" />
          <!-- 文件上传input 将它隐藏-->
          <el-upload
            ref="upload"
            class="upload-demo"
            action="https://upload.qiniup.com"
            :before-upload="beforeUpload"
            :data="qiniuForm"
            :on-success="uploadSuccess"
          >
            <el-button size="small" type="primary" class="uploadImage">点击上传</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetForm('ruleForm')">重置表单</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  ['link', 'image', 'video'],
  ['clean']
]

const { v4: uuidv4 } = require('uuid')
import { fetchUpload } from '@/api/upload'
import { updateNotice, fetchNotice } from '@/api/notice'

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      editorOption: {
        placeholder: '您想说点什么？',
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function(value) {
                if (value) {
                  document.querySelector('.uploadImage').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      notice: {
        title: '',
        content: ''
      },
      qiniuForm: {
        key: '', // 文件名称
        token: ''
      },
      rules: {
        title: [
          {
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 40,
            message: '长度在 3 到 40 个字符',
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入内容',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    // 查出当前要编辑的通知
    const id = this.$route.params.id
    fetchNotice(id).then((res) => {
      this.notice = res.data.notice
    })
  },
  methods: {
    // 上传之前
    async beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // 如果验证失败，返回假
      if (isJPG && isLt2M === false) return false
      // 如果验证成功，获取token
      const fileType = file.type === 'image/jpeg' ? 'jpg' : 'png' // 获取扩展名

      const res = await fetchUpload()
      this.qiniuForm = {
        key: `${uuidv4()}.${fileType}`, // 文件名称
        token: res.data.uploadToken
      }
      return true
    },
    // 上传成功
    uploadSuccess(res) {
      // 获取富文本组件实例
      const quill = this.$refs.QuillEditor.quill
      // 如果上传成功
      if (res) {
        const imgUrl = 'https://image.holyzq.com/' + res.key
        // 获取光标所在位置
        const length = quill.getSelection().index
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', imgUrl)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        updateNotice(this.notice.id, this.notice).then((res) => {
          if (res.code === 20000) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.$router.push({ name: 'Notice' })
          }
        })
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
.upload-demo {
  display: none;
}
</style>

